import React, { useEffect, useState } from 'react'
import { awaitWrap } from '@js/tool'
import { getFlowInstances, getFlowClass } from './ajax'
import { message, Skeleton } from 'antd'
import Instance from './components/Instance/Index'
import CreateBlock from './components/CreateBlock/Index'

// 初始化呈批实例数据
async function initInstances (caseid, flowKey, setLoading, setInstanceList, refreshCaseData) {
  setLoading(true)
  const [e, d] = await awaitWrap(getFlowInstances(caseid, flowKey))
  setLoading(false)
  if (e !== null) {
    message.error(e.message)
  } else {
    refreshCaseData && refreshCaseData()
    setInstanceList(d)
  }
}

// 初始化呈批定义
async function initFlowClass (flowKey, setLoading, setFLowClass) {
  setLoading(true)
  const [e, d] = await awaitWrap(getFlowClass(flowKey))
  setLoading(false)
  if (e !== null) {
    message.error(e.message)
  }
  setFLowClass(d)
}

function Index ({ flowKey, caseid, refreshCaseData }) {
  const [flowClass, setFlowClass] = useState(null)
  const [instanceList, setInstanceList] = useState([])
  const [instancesLoading, setInstancesLoading] = useState(false)
  const [classLoading, setClassLoading] = useState(false)
  useEffect(() => {
    initFlowClass(flowKey, setClassLoading, setFlowClass)
  }, [flowKey])
  useEffect(() => {
    initInstances(caseid, flowKey, setInstancesLoading, setInstanceList)
  }, [flowKey, caseid])
  return (
    <div>
      {
        !instancesLoading ? instanceList.map(li => {
          return <Instance key={li.id} data={li} refreshApprove={() => initInstances(caseid, flowKey, setInstancesLoading, setInstanceList, refreshCaseData)} />
        }) : (
          <Skeleton loading />
        )
      }
      {
        !classLoading && !instancesLoading && <CreateBlock flowClass={flowClass} instanceList={instanceList} caseid={caseid} refreshList={() => initInstances(caseid, flowKey, setInstancesLoading, setInstanceList, refreshCaseData)} />
      }
    </div>
  )
}

export default Index
